﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MAPDavy.Entities;
using System.Data.SqlClient;

namespace MAPDavy.Repository
{
    public class ScoreRepository:MasterRepository,IScoreRepository
    {

        public List<ScoreDTO> GetFromScoreByTermIdAndSeccionIdAndTestId(int termId, int seccionId, int testId)
        {
            var parmTerm = new SqlParameter("@TermId ", termId);
            var parmSeccion = new SqlParameter("@SeccionId", seccionId);
            var parmTest = new SqlParameter("@TestId", testId);

            object[] param = new object[3];
            param[0] = parmTerm;
            param[1] = parmSeccion;
            param[2] = parmTest;

            var query = Context.Database.SqlQuery<ScoreDTO>("GetFromScoreByTermIdAndSeccionIdAndTest @TermId,@SeccionId,@TestId", param).ToList();

            return query.ToList();
        }

        public List<ScoreDTO> GetFromScoreByTermIdAndGradeIdAndTest(int termId, int gradeId, int testId)
        {
            var parmTerm = new SqlParameter("@TermId ", termId);
            var parmSeccion = new SqlParameter("@GradeId", gradeId);
            var parmTest = new SqlParameter("@TestId", testId);

            object[] param = new object[3];
            param[0] = parmTerm;
            param[1] = parmSeccion;
            param[2] = parmTest;

            var query = Context.Database.SqlQuery<ScoreDTO>("GetFromScoreByTermIdAndGradeIdAndTest @TermId,@GradeId,@TestId", param).ToList();

            return query.ToList();
        }


        public void RegistrarScore(Score score)
        {
            var existe = (from s in Context.Scores
                         where s.Id == score.Id
                         select s).SingleOrDefault();

            if (existe ==null)
            {
                Context.Scores.Add(score);
                Context.SaveChanges();  
            }
            else
            {
                existe.RIT = score.RIT; 
                Context.Entry(existe).State = System.Data.EntityState.Modified;
                Context.SaveChanges(); 
            }
        }


        public int RegistrarScore(List<Score> scores)
        {
            foreach (var item in scores)
            {
                var existe = (from s in Context.Scores
                              where s.Id == item.Id
                              select s).SingleOrDefault();

                if (existe == null)
                {
                    Context.Scores.Add(item);                    
                }
                else
                {
                    existe.RIT = item.RIT;
                    Context.Entry(existe).State = System.Data.EntityState.Modified;
                }
            }

            return Context.SaveChanges();
        }
    }
}
